package com.spring.web.adminmanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.spring.web.adminmanage.common.PageResult;
import com.spring.web.adminmanage.entities.Role;
import com.spring.web.adminmanage.entities.RoleMenuRela;
import com.spring.web.adminmanage.repository.RoleDao;
import com.spring.web.adminmanage.repository.RoleMenuRelaDao;
import com.spring.web.adminmanage.service.RoleMenuRelaService;
import com.spring.web.adminmanage.service.RoleService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.List;


@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
	
	@Autowired
	RoleDao roleDao;
	@Autowired
	RoleMenuRelaDao roleMenuRelaDao;
	@Autowired
	RoleMenuRelaService roleMenuRelaService;
	@Override
	public PageResult<Role> selectToPageResult(Integer pageNumber, Integer pageSize, String rolename){
		PageHelper.startPage(pageNumber, pageSize);
		Example example = new Example(Role.class);
		if (!StringUtil.isEmpty(rolename)) {
			Criteria criteria = example.createCriteria();
			criteria.andLike("rolename", "%"+rolename+"%");
		}
		PageInfo<Role> pageinfo = new PageInfo<Role>(roleDao.selectByExample(example));
		return new PageResult<Role>(pageinfo);
	}
	@Override
	public List<Long> getOwnedMenuId(Long roleid) {
		return roleDao.getOwnedMenuId(roleid);
	}
	@Override
	public void update(Role role, List<String> oml) {
		roleDao.updateByPrimaryKeySelective(role);
		this.updateOwnedMenu(role, oml);
	}
	@Override
	public void insert(Role role, List<String> oml) {
		roleDao.insertBackId(role);
		Long roleid =role.getId();
		role.setId(roleid);
		this.updateOwnedMenu(role, oml);
	}
	
	@SuppressWarnings("unchecked")
	public void updateOwnedMenu(Role role, List<String> oml) {
		RoleMenuRela rolere = new RoleMenuRela(role.getId(),null);
		List<RoleMenuRela> rolereList = roleMenuRelaDao.select(rolere);
		List<Long> omList = new ArrayList<>();
		List<Long> ymList = new ArrayList<>();
		for (int i = 0; i < oml.size(); i++) {
			omList.add(new Long(oml.get(i)));
		}
		for (int i = 0; i < rolereList.size(); i++) {
			ymList.add(rolereList.get(i).getMenuid());
		}
		List<Long> addList = (List<Long>) CollectionUtils.subtract(omList,ymList);
		List<Long> delList = (List<Long>) CollectionUtils.subtract(ymList,omList);
		for (int i = 0; i < addList.size(); i++) {
			roleMenuRelaDao.insert(new RoleMenuRela(role.getId(), addList.get(i)));
		}
		for (int i = 0; i < delList.size(); i++) {
			roleMenuRelaDao.delete(new RoleMenuRela(role.getId(), delList.get(i)));
		}
	}
}